package patternrecognition;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import patternrecognition.symbols.forms.Coordinate;
import patternrecognition.symbols.forms.FilledRectangle;
import patternrecognition.symbols.forms.Rectangle;
import patternrecognition.symbols.forms.UnfilledRectangle;

public class Util {

	public static final int MAX_SIZE = 10;

	public static int[][] readFile(String fileName) {
		int[][] matrix = new int[MAX_SIZE][MAX_SIZE];
		try {
			BufferedReader input = new BufferedReader(new FileReader(
					"resources/" + fileName));
			try {
				int i = 0;
				String line = null;
				while ((line = input.readLine()) != null && i < MAX_SIZE) {
					char[] charArray = line.toCharArray();
					for (int j = 0; j < MAX_SIZE; j++) {
						matrix[i][j] = charArray[j] == '0' ? 0 : 1;
					}
					i++;
				}
			} finally {
				input.close();
			}
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return matrix;
	}

	public static List<String> parseMatrix(final int[][] matrix) {
		List<String> rows = new ArrayList<String>(MAX_SIZE);
		for (int row = 0; row < MAX_SIZE; row++) {
			StringBuilder sb = new StringBuilder(MAX_SIZE);
			for (int column = 0; column < MAX_SIZE; column++) {
				sb.append(matrix[row][column]);
			}
			rows.add(sb.toString());
		}
		return rows;
	}

	public static List<Rectangle> parseRows(final List<String> rows) {
		List<Rectangle> rectangles = new ArrayList<Rectangle>(1);
		for (int iFirstRow = 0; iFirstRow < MAX_SIZE; iFirstRow++) {
			String firstRow = rows.get(iFirstRow);
			if (isLine(firstRow) || isLimited(firstRow)) {
				int iLastRow = iFirstRow + 1;
				while (iLastRow < MAX_SIZE
						&& rows.get(iLastRow).equals(firstRow)) {
					iLastRow++;
				}
				int xLeft = firstRow.indexOf('1');
				int xRight = firstRow.lastIndexOf('1');
				Coordinate upperLeft = new Coordinate(xLeft, iFirstRow);
				Coordinate lowerRight = new Coordinate(xRight, iLastRow - 1);

				Rectangle rectangle = isLimited(firstRow) ? new UnfilledRectangle(
						upperLeft, lowerRight) : new FilledRectangle(upperLeft,
						lowerRight);
				rectangles.add(rectangle);

				iFirstRow = iLastRow - 1;
			}
		}
		return rectangles;
	}

	private static boolean isLine(final String aString) {
		return aString.matches("0*1+0*");
	}

	private static boolean isLimited(final String aString) {
		return aString.matches("0*1+0+1+0*");
	}
}
